import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  // process.env.VUE_APP_BASE_API 当前开发环境
  // 环境文件.env 开发 生产 测试
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})
// axios如  get请求 用params 传参 如果post请求 用data传参

// 请求拦截器
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // 每个接口都会进入的函数
    // config  .data .headers .url .method
    // 根据请求的信息 去拦截和配置

    if (store.getters.token) { // vuex存储过token 就添加到请求头
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // 携带token 到请求头
      // X - Token  token验证类型
      // 'key' :'value' 自定义内容
      //
      // config.headers['X-Token'] = getToken()
      // 在请求头上携带token 的内容
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */
  // 每个接口的返回数据阶段 都会进入
  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // 响应拦截器 根据公司的公共的状态 提示
    if (response.data.code === 401) {

    }
    if (response.data.code === 403) {
      // 禁止访问
    }
    if (response.data.code === 700) {
      // 暂无数据
    }
    // if the custom code is not 20000, it is judged as an error.
    return res
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
